package com.jml.生产者消费者.葛一鸣书;


import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author:jml
 * @date: 2019/6/19 0019 22:23
 * @description：
 */

public class Producer_Book implements Runnable {

    private volatile boolean isRunning = true;

    private BlockingQueue<PCData> queue;                       //内存缓冲区

    private static AtomicInteger count = new AtomicInteger();    //总数，原子操作

    private static final int SLEEPTIME = 1000;

    public Producer_Book(BlockingQueue<PCData> queue) {
        this.queue = queue;
    }

    public void run() {
        PCData data = null;
        Random r = new Random();

        System.out.println("start producer id=" + Thread.currentThread().getId());
        try {
            while (isRunning) {

                Thread.sleep(r.nextInt(SLEEPTIME));
                data = new PCData(count.incrementAndGet());      //构造任务数据
                System.out.println(data + "  放入队列线程：" + Thread.currentThread()
                        .getId()/*+"   地址："+count.toString()*/);

                //两秒之内放入队列
                if (!queue.offer(data, 2, TimeUnit.SECONDS)) {   //提交数据到缓冲区中
                    System.err.println("failed to put data：" + data);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
    }

    public void stop() {
        isRunning = false;
    }
}
